package com.application.api;

import com.application.common.Constant;
import com.application.module.couponget.CouponGet;
import com.application.module.couponget.CouponGetValidator;
import com.application.module.couponused.CouponUsed;
import com.application.module.courseitem.CourseItem;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.platform.annotation.Controller;
import com.platform.mvc.base.BaseController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户优惠券
 */
@Controller("/api/couponGet")
public class CouponGetApiController extends BaseController {

    /**
     * 获取我的优惠券数量
     */
    public void getNum() {
        int userid = getCUserId();
        //获取解锁券点播券
        int unlocks = CouponGet.dao.findAvailableNum(userid, CouponGet.TYPE_UNLOCK);
        int plays = CouponGet.dao.findAvailableNum(userid, CouponGet.TYPE_PLAY);
        Map<String, Object> map = new HashMap<>();
        map.put("unlocks", unlocks);
        map.put("plays", plays);
        success(map);
    }

    /*
    解锁课时
     */
    @Before({CouponGetValidator.class, Tx.class})
    public void unlock() {
        int itemId = getParaToInt("courseItemId");
        int type = getParaToInt("type", 1);
        int userid = getCUserId();

        CourseItem item = CourseItem.dao.findById(itemId);
        int needs = Constant.group_vip.equalsIgnoreCase(getCUser().getRoleId()) ? item.getItem_unlocks_vip() : item.getItem_unlocks();

        if (type == 1) {
            List<CouponGet> list = CouponGet.dao.findUnlockList(userid);
            //判断解锁券是否足够
            List<CouponGet> tmp = new ArrayList<>();
            int has = 0;
            for (CouponGet o : list) {
                tmp.add(o);
                has += o.getAmount() - o.getCost();
                if (has >= needs) {
                    o.setCost(o.getAmount()-(has-needs));
                    break;
                } else {
                    o.setCost(o.getAmount());
                }
            }
            if(has < needs) {
                error(400, "可用解锁券数量不够");
                return;
            }

            //插入消耗记录表
            CouponUsed.dao.addUnlock(userid, tmp, item, needs);
        } else {
            List<CouponGet> list = CouponGet.dao.findPlaysList(userid);
            if(list.size() < 1) {
                error(400, "可用点播券数量不够");
                return;
            }
            //插入消耗记录表
            CouponUsed.dao.addPlay(userid, list.get(0), item);
        }

        success(1);
    }
}
